//
//  XJCommunityViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/5/30.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJCommunityViewController.h"

// 两部分:上面:自定义头view  + 下面:collectionview
// View
#import "XJCommunityHeaderView.h"
#import "XJCommunityItem.h"
#import "XJCommunitySectionHeaderView.h"


#import "XJCommunityTagModel.h"
#import "XJCommunityCategoryModel.h"

//Controller
#import "XJCommunityIWantServeController.h" // 我要服务
#import "XJCommunitySearchViewController.h" // 搜索
#import "XJCmtIdentityVC.h" // 社区认证vc
#import "XJCustomIdentityViewController.h" // 实名认证
#import "XJCmtChargeViewController.h" //充值缴费

@interface XJCommunityViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>


@property(nonatomic, strong)XJCommunityHeaderView *headerView;
@property(nonatomic, strong) UICollectionView *clv;

@property(nonatomic, strong) NSMutableArray <XJCommunityCategoryModel *>*dataArray;
/**社区tag 数组*/
@property(nonatomic, strong) NSMutableArray *communityTagArr;
/**青年公社tag 数组*/
@property(nonatomic, strong) NSMutableArray *younthCommuneArr;
/**物业tag 数组*/
@property(nonatomic, strong) NSMutableArray *wuYeArr;

/**测试arr*/
@property(nonatomic, strong) NSMutableArray *testArr;

/**记录下社区id 其他页面的请求参数 ✅*/
@property (nonatomic, copy) NSString *communityId;
/**是否进行了实名认证状态: 1为正在审核，2审核通过，3为审核失败*/
@property (nonatomic, copy) NSString *customIdentityState;
/**是否进行了社区认证状态: 1为正在审核，2审核通过，3为审核失败*/
@property (nonatomic, copy) NSString *ctyIdentityState;


@end

@implementation XJCommunityViewController

#pragma mark - 一 lazy
- (XJCommunityHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[XJCommunityHeaderView alloc] initWithFrame:CGRectMake(0, 0,KWidth, ADAPTHeight(150))];
    }
    return _headerView;
}

- (UICollectionView *)clv{
    if (!_clv) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        //设置clv左右间距
        layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
        
        _clv = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 150, KWidth, KHeight-150-XJTopNavH) collectionViewLayout:layout];
        _clv.backgroundColor = [UIColor  whiteColor];
        
        _clv.delegate = self;
        _clv.dataSource = self;
        
        [_clv registerClass:[XJCommunityItem class] forCellWithReuseIdentifier:@"XJCommunityItemId"];
        [_clv registerClass:[XJCommunitySectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"XJCommunitySectionHeaderViewId"];
    }
    return _clv;
}
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)testArr {
    if (!_testArr) {
        _testArr = [NSMutableArray array];
    }
    return _testArr;
}



#pragma mark - 二 视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self requestData];
    [self setupNav];
    
    [self setupView];
    
    XJLog(@"111111*-*-*-*-*-*-*");
}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//
//    XJLog(@"社区id是:%@",self.communityId);
//    XJLog(@"22222*-*-*-*-*-*-*");
//}
- (void)setupView{
    [self.view addSubview:self.headerView];
 
    [self.view addSubview:self.clv];
}

- (void)setupNav{
    self.navTitle = @"社区";

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(communitySearchButtonAction)];
}
- (void)communitySearchButtonAction{
    XJLog(@"点击----》》搜索");
    XJCommunitySearchViewController *communitySerchVC = [[XJCommunitySearchViewController alloc] init];
    communitySerchVC.lat = self.lat;
    communitySerchVC.lng = self.lng;
    
    XJWeakSelf(self);
    
//    communitySerchVC.communitySearchVCBlock = ^(NSString *communityName, NSString *address) {
//
//        [weakself.headerView reConfigureName:communityName address:address];
//    };
    
    //重新进行网路请求
    communitySerchVC.communitySearchVCRefreshBlock = ^(NSString *community_id) {
        [weakself requestRefreshDataWithCommunityId:community_id];
    };
    
    [self.navigationController pushViewController:communitySerchVC animated:YES];
}

#pragma mark - 二 视图生命周期
#pragma mark - 三 网络请求
- (void)requestData{
    
    [XJHttpTool requestCommunityNearestWithLng:self.lng lat:self.lat successH:^(id responseObjc) {
        
//        XJLog(@"成功:%@",jsonStr);
        NSNumber *code = responseObjc[@"code"];
        if ([code isEqualToNumber:@0]) {
            [self xj_deassignWithDic:responseObjc];
        }else {
            [MBProgressHUD showError:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        XJLog(@"失败%@",error);
    }];
    
    //    -120.189459--经纬度:30.194977
    //    http://xinjiangapi.zertone1.com/api/v1/community/nearest?lat=30.194898&lng=120.18948
}

/**根据回调过来的社区id 重新请求本页数据*/
- (void)requestRefreshDataWithCommunityId:(NSString *)community_id {
    
    NSString * customer_id = [XJUserModel xj_customId];
    
    if ([NSString isEmptyString:customer_id]) return;
    [XJHttpTool requestCommunityEnterCommunity_id:community_id customer_id:customer_id successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            [self xj_deassignWithDic:responseObjc];
        }
    } failH:^(NSError *error) {
    }];
}

/**deassign 重新赋值 */
- (void)xj_deassignWithDic:(NSDictionary *)responseObjc {
    NSDictionary *contentDic =  responseObjc[@"data"][@"content"];
    
    {
        //如果之前有数据的话 把之前的结果清空
        [self.dataArray removeAllObjects];
        [self.testArr removeAllObjects];
        self.communityId = @"";
    }
    
    self.dataArray =   [XJCommunityCategoryModel mj_objectArrayWithKeyValuesArray:contentDic[@"category"]];
    
    // 防空判断
    if (self.dataArray.count == 0) {
        return ;
    }
    // 社区+青年公社   +  物业 三个分类是固定的。
    
    [self.testArr addObject:[self.dataArray firstObject]];
    [self.testArr addObject:[self.dataArray lastObject]];
    //            NSLog(@"%@",self.testArr);
    XJLog(@"%@",[self.dataArray lastObject].name);
    
    NSDictionary *communityDic = contentDic[@"community"];
    NSString *avatar = communityDic[@"avatar"];
    NSString *address = communityDic[@"address"];
    NSString *name = communityDic[@"name"];
    NSString *cover = communityDic[@"cover"];
    // 服务器返回的是NSNumber 必选要转为NSString。雪崩
    self.communityId = [NSString stringWithFormat:@"%@",communityDic[@"id"]];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.headerView configureBgImageStr:cover iconStr:avatar name:name address:address];
        [self.clv reloadData];
    });
}

// 是否进行了实名认证
- (void)requestIsCustomIdentityWithSemaphore:(dispatch_semaphore_t)semap {
    
    [XJHttpTool requestCustomIsIdentitySuccesH:^(id responseObjc) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        XJLog(@"是否进行了实名认证:%@",jsonStr);
        XJLog(@"11111111111111111===========>");
        
        self.customIdentityState = [NSString stringWithFormat:@"%@",responseObjc[@"data"][@"identity"][@"status"]];
        
        dispatch_semaphore_signal(semap);
    } failH:^(NSError *error) {
        dispatch_semaphore_signal(semap);
    }];
    
    dispatch_semaphore_wait(semap, DISPATCH_TIME_FOREVER);
}

// 是否进行了社区认证
- (void)requestIsCmtIdentityWithSemaphore:(dispatch_semaphore_t)semaP {
    if ([NSString isEmptyString:self.communityId]) {
        XJLog(@"communityId请求参数为空操作无效");
        return;
    }
    
    [XJHttpTool requestCommunityIdentityIsIdentityWithCmtId:self.communityId successH:^(id responseObjc) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        XJLog(@"是否进行了社区认证:%@",jsonStr);
        XJLog(@"22222222222222=============>");
        self.ctyIdentityState = [NSString stringWithFormat:@"%@",responseObjc[@"data"][@"status"]];
        
        
        dispatch_semaphore_signal(semaP);

    } failH:^(NSError *error) {
        dispatch_semaphore_signal(semaP);
    }];
    
    dispatch_semaphore_wait(semaP, DISPATCH_TIME_FOREVER);
}



#pragma mark - 四 clv代理 UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.testArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // 区头两个 标签: 社区 + 青年公社
    XJCommunityCategoryModel *categoryM  =self.testArr[section];
   
    return categoryM.second_category.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    XJCommunityItem *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"XJCommunityItemId" forIndexPath:indexPath];

    
    //防空判断
    if (self.dataArray.count) {
        XJCommunityCategoryModel *categoryM = self.testArr[indexPath.section];
        XJCommunityTagModel *tagModel = categoryM.second_category[indexPath.row];
        [item configureIconImgStr:tagModel.cover tagStr:tagModel.name];
    }
   
    return item;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    // 区头
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        XJCommunitySectionHeaderView *sectionHeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"XJCommunitySectionHeaderViewId" forIndexPath:indexPath];
        
        
        //防空判断:前提:数组一定要有数据
        if (self.dataArray.count) {
            if (indexPath.section == 0) {
                [sectionHeaderView configureXJCommunitySectionHeaderViewHideSecondButton:NO WithFirsttitle:@"社区" secondTitle:@"青年公社"];
                
            }else {
                [sectionHeaderView configureXJCommunitySectionHeaderViewHideSecondButton:YES WithFirsttitle:@"物业" secondTitle:@"哈哈哈哈"];
            }
            // 思想:寻找不变量
            // 这三个按钮是固定的:社区 + 青年公社 + 物业 按钮
            
            // 单刷新某一个section 不要全部刷新
            sectionHeaderView.communtiySectionHeaderViewFirstButtonBlock = ^{
                self.testArr[0] = self.dataArray[0];
                
                XJLog(@"%@",self.testArr);
                // 刷新第一个section
                NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
                
                [self.clv reloadSections:set];
            };
            sectionHeaderView.communitySectionHeaderViewSecondButtonBlock = ^{
                self.testArr[0] = self.dataArray[1];
                XJLog(@"%@",self.testArr);
                // 刷新第一个section
                NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
                
                [self.clv reloadSections:set];
                
                
            };
        }
       
        return sectionHeaderView;
    }else{
        return nil;
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    return CGSizeMake(KWidth, 50);
}

#pragma mark - item宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat itemW = (KWidth-8) /5 ;
    //9宫格组
    return CGSizeMake(itemW , itemW + XJMargin);
//    return CGSizeMake((KWidth-XJMargin*6)/5 , KWidth/5 + XJMargin);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 2;
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    // 防空判断
    if (self.dataArray.count) {
        XJCommunityCategoryModel *model = self.testArr[indexPath.section];
        
        XJCommunityTagModel *tagModel = model.second_category[indexPath.row];
       
        [self goToDifferenceVCWithModel:tagModel];
    }
}

#pragma mark - 五 业务逻辑
//跳转到不同的vc
- (void)goToDifferenceVCWithModel:(XJCommunityTagModel *)tagModel {
    [self goToIWantServeVCWithModel:tagModel]; //跳转到我要服务VC
    
    [self goToCmtIdVCWithModel:tagModel]; //社区认证

    [self goToCmtChargeVCWithModel:tagModel]; //充值缴费
}

/**跳转到我要服务vc*/
- (void)goToIWantServeVCWithModel:(XJCommunityTagModel *)tagModel {
    XJLog(@"点击了:====>%@",tagModel.name);
    if ([tagModel.name isEqualToString:@"我要服务"]) {
        // 跳转
        XJCommunityIWantServeController *iWantServeVC = [[XJCommunityIWantServeController alloc] init];
        iWantServeVC.community_id = self.communityId;
        [self.navigationController pushViewController:iWantServeVC animated:YES];
    }
}

/**跳转社区认证vc*/
- (void)goToCmtIdVCWithModel:(XJCommunityTagModel *)tagModel {
    XJLog(@"点击了:=====>%@",tagModel.name);
    if ([tagModel.name isEqualToString:@"社区认证"]) {

        //是时候用用信号量了。
        [self requestBySemaphore];
    }
}

- (void)requestBySemaphore {
    //创建信号量:初始值为0
    dispatch_semaphore_t semap = dispatch_semaphore_create(0);
    //创建队列
    dispatch_queue_t queue1 = dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(queue1, ^{
        [self requestIsCustomIdentityWithSemaphore:semap];
        [self requestIsCmtIdentityWithSemaphore:semap];
        [self skipToSpecifiedVC];
    });
}


- (void)skipToSpecifiedVC{
    XJLog(@"到这里来了 请跳转界面");
    // 判断状态
    // 是否通过了实名认证 是-->判断是否通过了社区认证   否 --->跳转实名认证
    // 是否通过了社区认证 是-->显示认证结果           否 --->去社区认证
    
    /**是否进行了实名认证状态: 1为正在审核，2审核通过，3为审核失败*/

    BOOL isCustomIdentity = [self.customIdentityState isEqualToString:@"2"] ? YES : NO;
    BOOL isCtyIdentity = [self.ctyIdentityState isEqualToString:@"2"] ? YES : NO;
    
    if (isCustomIdentity && isCtyIdentity) { //实名认证、社区认证都通过
        XJLog(@"实名认证、社区认证都通过");
    }else if (isCustomIdentity && !isCtyIdentity) { // 实名认证YES 社区认证NO
        XJLog(@"实名认证YES 社区认证NO");
        XJLog(@"%@",[NSThread currentThread]);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            XJCmtIdentityVC *cmtIdVC = [[XJCmtIdentityVC alloc] init];
            [self.navigationController pushViewController:cmtIdVC animated:YES];
            cmtIdVC.communityId = self.communityId;
        });
        
    }else { //都认为是没有通过实名认证 弹框:请先进行实名认证
        XJLog(@"都认为是没有通过实名认证");
        
        [self pleaseCutomIdentityFirstAlert];
    }
    //跳转
//    XJCmtIdentityVC *cmtIdVC = [[XJCmtIdentityVC alloc] init];
//    [self.navigationController pushViewController:cmtIdVC animated:YES];
}

/***请先进行实名认证弹框*/
- (void)pleaseCutomIdentityFirstAlert {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"请先进行实名认证" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        XJCustomIdentityViewController *customIDentityVC = [[XJCustomIdentityViewController alloc] init];
        [self.navigationController pushViewController:customIDentityVC animated:YES];
    }];
    
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

/**跳转充值缴费vc*/
- (void)goToCmtChargeVCWithModel:(XJCommunityTagModel *)tagModel {
    XJLog(@"点击了:%@",tagModel.name);
    if ([tagModel.tagId isEqualToNumber:@36]) { //跳转社区缴费
        
        [XJHttpTool requestCustomIsIdentitySuccesH:^(id responseObjc) {
            NSString *status  = [NSString stringWithFormat:@"%@",responseObjc[@"data"][@"identity"][@"status"]];
            if ([status isEqualToString:@"2"]) {
                XJCmtChargeViewController *cmtChargeVC = [[XJCmtChargeViewController alloc] init];
                cmtChargeVC.cmtId = self.communityId;
                //如果为空不让跳转
                if (![NSString isEmptyString:self.communityId]) {
                    [self.navigationController pushViewController:cmtChargeVC animated:YES];
                }
            }else {
                if (![self.ctyIdentityState isEqualToString:@"2"]) {
                    [JRToast showWithText:@"未来巴扎:请先进行社区认证"];
                    return;
                }
            }
        } failH:^(NSError *error) {
            
        }];
    }
}

#pragma mark - 六 问题
/**
 1.多个网络请求请求顺序问题
 一进来就先请求本界面的请求数据。有一个 社区id community_id 是其他网络请求的请求参数
 
 问题搞复杂了。点击的时候我再判断是否进行了实名认证、和社区认证 同时调用两个请求。（请求结果用2个变量进行记录）
 
 
 
 */

@end
